package org.example.controller;

import brave.Span;
import brave.Tracer;
import brave.Tracing;
import brave.propagation.CurrentTraceContext;
import brave.propagation.Propagation;
import brave.propagation.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class ProviderController {

    @Autowired
    Tracing tracing;
    Propagation.RemoteGetter<HttpServletRequest> GETTER = new Propagation.RemoteGetter<HttpServletRequest>() {
        @Override
        public Span.Kind spanKind() {
            return Span.Kind.SERVER;
        }

        @Override
        public String get(HttpServletRequest request, String name) {
            return request.getHeader(name);
        }
    };

    @GetMapping("provide")
    public String provide(HttpServletRequest request, HttpServletResponse response) {
        String result = null;
        CurrentTraceContext currentTraceContext = tracing.currentTraceContext();

        TraceContext context = (TraceContext) request.getAttribute(TraceContext.class.getName());
        if (context != null) {
            CurrentTraceContext.Scope scope = currentTraceContext.maybeScope(context);
            try {
                result = process();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                scope.close();
            }
            return result;
        }

        TraceContext.Extractor<HttpServletRequest> extractor = tracing.propagation().extractor(GETTER);
        Tracer tracer = tracing.tracer();
        Span span = tracer.nextSpan(extractor.extract(request)).name("provide");
        span.start();
        CurrentTraceContext.Scope scope = currentTraceContext.newScope(span.context());
        try /*(Tracer.SpanInScope ws = tracer.withSpanInScope(span))*/ {
            result = process();
        } catch (Exception e) {
            span.error(e);
            e.printStackTrace();
        } finally {
            span.kind(Span.Kind.SERVER);
            span.finish();
            scope.close();
        }

        return result;
    }

    private String process() throws InterruptedException {
        Thread.sleep(200);
        return "provider server processing...";
    }
}
